package com.geek.framework.study.config.microprofile.converter;

import org.eclipse.microprofile.config.spi.Converter;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;

public class Converters implements Iterable<Converter> {

    private List<Converter> converterList = new ArrayList<>();

    private Map<ConvertEntry, Converter> convertMap = new HashMap<>();


    public void addConverters(Converter... converters) {
        for (Converter converter : converters) {
            converterList.add(converter);
            convertMap.put(ConvertEntry.stringSourceEntry(getConverterType(converter)), converter);
        }
    }

    public Converter matchConverter(String source, Class<?> clazz) {
        ConvertEntry sourceEntry = ConvertEntry.stringSourceEntry(clazz);
        if (sourceEntry == null) {
            return null;
        }
        return convertMap.get(sourceEntry);
    }




    @Override
    public Iterator<Converter> iterator() {
        return converterList.iterator();
    }

    /**
     * 获取泛型的类型
     * @see com.geek.framework.study.ReflectiveDemo#test()
     * @param converter
     * @return
     */
    private Class<?> getConverterType(Converter converter) {
        Type superclass = converter.getClass().getGenericSuperclass();
        if (superclass instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) superclass;
            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            if (actualTypeArguments != null && actualTypeArguments.length > 0) {
                return (Class<?>) actualTypeArguments[0];
            }
        }
        return null;
    }

}
